﻿using Janus.BaseEntitys;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Janus.Cores.Extension
{
    public static class EntityExtension
    {
        public static Hashtable ToHashtable(this Entity model)
        {
            Hashtable table = new Hashtable();
            var type = model.GetType();
            foreach (var p in type.GetProperties())
            {
                var val = p.GetValue(model, null);
                if (val != null)
                {
                    table.Add(p.Name, val);
                }
            }
            return table;
        }

        /// <summary>
        /// hashTable 转换为Entity
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hashtable"></param>
        /// <returns></returns>
        public static T ToEntity<T>(this Hashtable hashtable) where T : new()
        {
            T t = new T();
            foreach (var item in t.GetType().GetProperties())
            {
                if (hashtable.ContainsKey(item.Name))
                {
                    item.SetValue(t, hashtable[item.Name], null);
                }
            }
            return t;
        }

        /// <summary>
        /// hashTable 转换为Entity
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hashtable"></param>
        /// <returns></returns>
        public static List<T> ToEntity<T>(this IList<Hashtable> hashtable) where T :  new()
        {
            List<T> t = new List<T>();
            foreach (var item in hashtable)
            {
                var result = item.ToEntity<T>();
                t.Add(result);
            }

            return t;
        }
    }
}
